//
//  HTempViewController.m
//  HDesign
//
//  Created by admin on 4/25/14.
//  Copyright (c) 2014 admin. All rights reserved.
//

#import "HTempViewController.h"
#import "UIMenuController+Associate.h"
#import "UIColor+Random.h"
#import "UIGestureRecognizer+DraggingAdditions.h"

#import <objc/runtime.h>
#define CWIDTH 100
#define CHEIGHT 80
@interface HTempViewController ()

@end

@implementation HTempViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.evaluateViews = [[NSMutableArray alloc] init];
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"viewWillAppear:%d, %@", animated, self);
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"viewDidAppear:%d, %@", animated, self);
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    NSLog(@"viewWillDisappear:%d, %@", animated, self);
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    NSLog(@"viewDidDisappear:%d, %@", animated, self);
}

- (void)viewWillShrinkInExposeController:(LIExposeController *)exposeController animated:(BOOL)animated {
    NSLog(@"viewWillShrinkInExposeController:%d, %@", animated, self);
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewDidShrinkInExposeController:(LIExposeController *)exposeController animated:(BOOL)animated {
    NSLog(@"viewDidShrinkInExposeController:%d, %@", animated, self);
}

- (void)viewWillExpandInExposeController:(LIExposeController *)exposeController animated:(BOOL)animated {
    NSLog(@"viewWillExpandInExposeController:%d, %@", animated, self);
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidExpandInExposeController:(LIExposeController *)exposeController animated:(BOOL)animated {
    NSLog(@"viewDidExpandInExposeController:%d, %@", animated, self);
}
#pragma mark 预览视图
-(void)previewView{
    
    isEdit = !isEdit;
    
    [self hideborder];
    if (isEdit) {
        _placeholderView.hidden = YES;
        NSLog(@"index - %lu",(unsigned long)[self.view.subviews indexOfObject:_placeholderView]);
//        移除坐标视图
//        for (UIView * view in self.view.subviews) {
//            if ([view isKindOfClass:[PAPlaceholderView class]]) {
//                [view removeFromSuperview];
//            }
//        }
//        改变左标题为编辑
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"编辑", @"edit")
                                                                                 style:UIBarButtonItemStyleBordered
                                                                                target:self
                                                                                action:@selector(previewView)];
    }else{
     
        _placeholderView.hidden = NO;
        for (UIView * view in self.view.subviews) {
            if ([view isKindOfClass:[SPUserResizableView class]]) {
                SPUserResizableView * spuserview = (SPUserResizableView *)view;
                [spuserview showEditingHandles];
            }
        }
       NSLog(@"index - %lu",(unsigned long)[self.view.subviews indexOfObject:_placeholderView]);
//        改变左标题为预览
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"预览", @"preview")
                                                                                 style:UIBarButtonItemStyleBordered
                                                                                target:self
                                                                                action:@selector(previewView)];
        [UIView animateWithDuration:0.7 delay:0 options:0 animations:^(){
            _placeholderView.alpha = 0.2;
//            [self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
            _placeholderView.alpha = 1;
        } completion:^(BOOL finished)
        {
           
        }];
        
    }
   

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.toolbarHidden = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"完成", @"expose_title")
                                                                               style:UIBarButtonItemStyleBordered
                                                                              target:self.navigationController.exposeController
                                                                              action:@selector(toggleExpose)];
    
    isflage = YES;
    isEdit = YES;
    
    [self.navigationController setNavigationBarHidden:isflage animated:YES];
    
//    初始化控件数组
    self.userControlArray = [[NSMutableArray alloc] init];
    
    self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
    self.leftSwipeGestureRecognizer.delegate = self;
    self.leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    
    
    [self.view addGestureRecognizer:self.leftSwipeGestureRecognizer];
    self.rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
    self.rightSwipeGestureRecognizer.delegate = self;
    self.rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    
    _placeholderView = [[PAPlaceholderView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    self.view = _placeholderView;
    [self.view addSubview:_placeholderView];
    [self previewView];
    [self.view addGestureRecognizer:self.rightSwipeGestureRecognizer];

    self.panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanRecognizer:)];
}
- (void)onBurger:(id)sender {
    
    RNSideBarItem * sidebarButton = [[RNSideBarItem alloc] init];
    sidebarButton.imgbar = [UIImage imageNamed:@"Button.png"];
//    sidebarButton.colors = [UIColor colorWithRed:240/255.f green:159/255.f blue:254/255.f alpha:1];
    sidebarButton.title = @"Button";
    RNSideBarItem * sidebarLabel = [[RNSideBarItem alloc] init];
    sidebarLabel.colors = [UIColor colorWithRed:240/255.f green:159/255.f blue:254/255.f alpha:1];
    sidebarLabel.imgbar = [UIImage imageNamed:@"Label.png"];
    
    sidebarLabel.title = @"Label";

    RNSideBarItem * sidebarSegmented = [[RNSideBarItem alloc] init];
    sidebarSegmented.imgbar = [UIImage imageNamed:@"Segmented Control.png"];
    sidebarSegmented.colors = [UIColor colorWithRed:240/255.f green:159/255.f blue:254/255.f alpha:1];
    sidebarSegmented.title = @"Segmented Control";
    
    
    RNSideBarItem * sidebarTextField = [[RNSideBarItem alloc] init];
    sidebarTextField.imgbar = [UIImage imageNamed:@"Text.png"];
    sidebarTextField.colors = [UIColor randomColor];
    sidebarTextField.title = @"Text Field";
    
    
    RNSideBarItem * sidebarSlider = [[RNSideBarItem alloc] init];
    sidebarSlider.imgbar = [UIImage imageNamed:@"Slider.png"];
    sidebarSlider.colors = [UIColor randomColor];
    sidebarSlider.title = @"Slider";
    
    RNSideBarItem * sidebarSwitch = [[RNSideBarItem alloc] init];
    sidebarSwitch.imgbar = [UIImage imageNamed:@"Switch.png"];
    sidebarSwitch.colors = [UIColor randomColor];
    sidebarSwitch.title = @"Switch";
    
    RNSideBarItem * sidebarView = [[RNSideBarItem alloc] init];
    sidebarView.imgbar = [UIImage imageNamed:@"UIView.png"];
    sidebarView.colors = [UIColor randomColor];
    sidebarView.title = @"UIView";
    
    
    NSArray * sidebararray = @[sidebarButton,sidebarLabel,sidebarSegmented,sidebarTextField,sidebarSlider,sidebarSwitch,sidebarView];
    
    self.controlArray = [[NSMutableArray alloc] initWithArray:sidebararray];
//    RNFrostedSidebar *callout = [[RNFrostedSidebar alloc] initWithImages:images selectedIndices:self.optionIndices borderColors:colors];
    RNFrostedSidebar *callout = [[RNFrostedSidebar alloc] initWithSideBarItem:sidebararray];
//    RNFrostedSidebar * callout = [[RNFrostedSidebar alloc] initWithSideBarItem:sidebararray selectedIndices:nil borderColors:colors];
    callout.delegate = self;
    //    callout.showFromRight = YES;
    [callout show];
}
#pragma mark - RNFrostedSidebarDelegate

- (void)sidebar:(RNFrostedSidebar *)sidebar didTapItemAtIndex:(NSUInteger)index {

    RNSideBarItem * sidebaritem = [self.controlArray objectAtIndex:index];
        NSLog(@"Tapped item at index %i  %@",index,sidebaritem.title);
    sidebaritem.tag = index;
    [self initUserControl:sidebaritem];

}
#pragma mark 初始化控件
-(void)initUserControl:(id)sender{
    SPUserResizableView *userResizableView  = nil;
    RNSideBarItem * sidebaritem = (RNSideBarItem * )sender;
    if ([sidebaritem.title isEqualToString:@"Button"]) {
        int valueHeight = (arc4random() % ((int)self.view.frame.size.height - CHEIGHT)) + 1;
        int valueWidth = (arc4random() % ((int)self.view.frame.size.width - CWIDTH)) + 1;
        // (1) Create a user resizable view with a simple red background content view.
        CGRect gripFrame = CGRectMake(valueWidth, valueHeight, CWIDTH, 50);
        userResizableView = [[SPUserResizableView alloc] initWithFrame:gripFrame];
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = [UIColor grayColor];
        [btn setTitle:@"btncccc" forState:UIControlStateNormal];
        userResizableView.contentControl = btn;
        
    }
    if ([sidebaritem.title isEqualToString:@"Label"]) {
        int valueHeight = (arc4random() % ((int)self.view.frame.size.height - CHEIGHT)) + 1;
        int valueWidth = (arc4random() % ((int)self.view.frame.size.width - CWIDTH)) + 1;
        // (1) Create a user resizable view with a simple red background content view.
        CGRect gripFrame = CGRectMake(valueWidth, valueHeight, CWIDTH, 50);
        userResizableView = [[SPUserResizableView alloc] initWithFrame:gripFrame];
        UILabel * lbl = [[UILabel alloc] init];
        lbl.text = @"label";
        userResizableView.contentView = lbl;
    }
    if ([sidebaritem.title isEqualToString:@"Segmented Control"]) {
        int valueHeight = (arc4random() % ((int)self.view.frame.size.height - CHEIGHT)) + 1;
        int valueWidth = (arc4random() % ((int)self.view.frame.size.width - CWIDTH)) + 1;
        // (1) Create a user resizable view with a simple red background content view.
        CGRect gripFrame = CGRectMake(valueWidth, valueHeight, CWIDTH, 50);
        userResizableView = [[SPUserResizableView alloc] initWithFrame:gripFrame];

        
        NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"1",@"2",@"3",@"4",nil];
        
        //初始化UISegmentedControl
        
        UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
        
        segmentedControl.frame = CGRectMake(20.0, 20.0, 250.0, 50.0);
        
        segmentedControl.selectedSegmentIndex = 1;//设置默认选择项索引
        
//        segmentedControl.tintColor = [UIColor blueColor];
        
        //有基本四种样式
        segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;//设置样
        userResizableView.contentControl = segmentedControl;
    }
    if ([sidebaritem.title isEqualToString:@"Text Field"]) {
        int valueHeight = (arc4random() % ((int)self.view.frame.size.height - CHEIGHT)) + 1;
        int valueWidth = (arc4random() % ((int)self.view.frame.size.width - CWIDTH)) + 1;
        // (1) Create a user resizable view with a simple red background content view.
        CGRect gripFrame = CGRectMake(valueWidth, valueHeight, CWIDTH, 50);
        userResizableView = [[SPUserResizableView alloc] initWithFrame:gripFrame];
        
        UITextField * txtfield = [[UITextField alloc] initWithFrame:gripFrame];
        txtfield.placeholder = @"Text Field";
        txtfield.borderStyle = UITextBorderStyleRoundedRect;
        userResizableView.contentControl = txtfield;
    }
    if ([sidebaritem.title isEqualToString:@"Slider"]) {
        int valueHeight = (arc4random() % ((int)self.view.frame.size.height - CHEIGHT)) + 1;
        int valueWidth = (arc4random() % ((int)self.view.frame.size.width - CWIDTH)) + 1;
        // (1) Create a user resizable view with a simple red background content view.
        CGRect gripFrame = CGRectMake(valueWidth, valueHeight, CWIDTH, 50);
        userResizableView = [[SPUserResizableView alloc] initWithFrame:gripFrame];
        
        UISlider *slider = [[UISlider alloc] initWithFrame:gripFrame];
//        ／／初始化
        slider.minimumValue = 0;
//        ／／指定可变最小值
        slider.maximumValue = 100;
//        ／／指定可变最大值
        slider.value = 50;
//        ／／指定初始值
        userResizableView.contentControl = slider;

    }
    if ([sidebaritem.title isEqualToString:@"Switch"]) {
        int valueHeight = (arc4random() % ((int)self.view.frame.size.height - CHEIGHT)) + 1;
        int valueWidth = (arc4random() % ((int)self.view.frame.size.width - CWIDTH)) + 1;
        // (1) Create a user resizable view with a simple red background content view.
        CGRect gripFrame = CGRectMake(valueWidth, valueHeight, CWIDTH, 50);
        userResizableView = [[SPUserResizableView alloc] initWithFrame:gripFrame];
        
        UISwitch *switchButton = [[UISwitch alloc] initWithFrame:gripFrame];
        [switchButton setOn:YES];
        userResizableView.contentControl = switchButton;
        [userResizableView addGestureRecognizer:self.panRecognizer];
       
    }
    /**
     *  UIView
     */
    if ([sidebaritem.title isEqualToString:@"UIView"]) {
        int valueHeight = (arc4random() % ((int)self.view.frame.size.height - CHEIGHT)) + 1;
        int valueWidth = (arc4random() % ((int)self.view.frame.size.width - CWIDTH)) + 1;
        // (1) Create a user resizable view with a simple red background content view.
        CGRect gripFrame = CGRectMake(valueWidth, valueHeight, CWIDTH, 50);
        userResizableView = [[SPUserResizableView alloc] initWithFrame:gripFrame];
        
        UIView * view = [[UIView alloc] initWithFrame:gripFrame];
        view.backgroundColor = [UIColor randomColor];
        userResizableView.contentView = view;
        
        [self.evaluateViews addObject:userResizableView];
    }
    userResizableView.delegate = self;
    [userResizableView showEditingHandles];
    
    [self.view addSubview:userResizableView];
    
//    [self.view bringSubviewToFront:userResizableView];
    [self.userControlArray addObject:userResizableView];
}
- (void)sidebar:(RNFrostedSidebar *)sidebar didEnable:(BOOL)itemEnabled itemAtIndex:(NSUInteger)index {
    if (itemEnabled) {
        [self.optionIndices addIndex:index];
    }
    else {
        [self.optionIndices removeIndex:index];
    }
}
#pragma mark 手势
- (void)handleSwipes:(UISwipeGestureRecognizer *)sender
{
    if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
        
        [self onBurger:nil];
    }
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft) {
        
    }
    
}
/**
 *  拖动手势
 *
 *  @param sender 手势对象
 */
- (void)handlePanRecognizer:(id)sender
{
    UIPanGestureRecognizer *recongizer = (UIPanGestureRecognizer *)sender;
    
    if ([recongizer state] == UIGestureRecognizerStateBegan)
    {
        NSLog(@"pan begin");
    }
    
    NSMutableArray *views = [self evaluateViews];

    UIView * recongizerView = recongizer.view;
    
    // Block to execute when our dragged view is contained by one of our evaluation views.
    static void (^overlappingBlock)(UIView *overlappingView);
    overlappingBlock = ^(UIView *overlappingView) {
        
        [views enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            
            UIView *aView = (UIView *)obj;
            
            // Style an overlapping view
            if (aView == overlappingView)
            {
                aView.layer.borderWidth = 8.0f;
                aView.layer.borderColor = [[UIColor redColor] CGColor];
            }
            // Remove styling on non-overlapping views
            else
            {
                aView.layer.borderWidth = 0.0f;
                if ([recongizerView.superview isEqual:self.view]) {
                    NSLog(@"remove");
                }
                
            
            }
        }];
    };
    
    // Block to execute when gesture ends.
    static void (^completionBlock)(UIView *overlappingView);
    completionBlock = ^(UIView *overlappingView) {
        
        if (overlappingView)
        {
            NSUInteger overlapIndex = [[self evaluateViews] indexOfObject:overlappingView];
            
   
            NSString *completionText = [NSString stringWithFormat:@"Released over view at index: %d", overlapIndex];
            if (![recongizerView.superview isEqual:overlappingView]) {
                [recongizer.view setFrame:CGRectMake(recongizer.view.frame.origin.x - overlappingView.frame.origin.x, recongizer.view.frame.origin.y - overlappingView.frame.origin.y, recongizer.view.frame.size.width, recongizer.view.frame.size.height)];
            }
            

            [overlappingView addSubview:recongizerView];
//            [recongizer.view removeGestureRecognizer:self.panRecognizer];

        }
        
        // Remove styling from all views
        [views enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            UIView *aView = (UIView *)obj;
            aView.layer.borderWidth = 0.0f;
            aView.layer.borderColor = [UIColor blueColor].CGColor;
            NSLog(@"%d",[views count]);

//            [recongizer.view removeFromSuperview];
        }];
    };
    
    [recongizer dragViewWithinView:[self view]
           evaluateViewsForOverlap:views
   containedByOverlappingViewBlock:overlappingBlock
                        completion:completionBlock];
    
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch{
//    NSLog(@"+%@",[touch.view class]);
    if ([[touch.view.class description] isEqualToString:@"SPGripViewBorderView"]) {
        return NO;
    }else{
        return YES;
    }
}
#pragma mark 取消编辑框
-(void)hideborder{
    for (UIView * view in self.view.subviews) {
        if ([view isKindOfClass:[SPUserResizableView class]]) {
            SPUserResizableView * spuserview = (SPUserResizableView *)view;
            [spuserview hideEditingHandles];
        }
    }

}
#pragma mark onClick
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    isflage = !isflage;
    [self.navigationController setNavigationBarHidden:isflage animated:YES];
}
#pragma mark userResizableViewDelegate
// Called when the resizable view receives touchesBegan: and activates the editing handles.
- (void)userResizableViewDidBeginEditing:(SPUserResizableView *)userResizableView{
    self.navigationController.interactivePopGestureRecognizer.enabled = NO ;
//    NSLog(@"当前控件数组中的index ＝ %lul",[self.userControlArray indexOfObject:userResizableView]);
    
    userResizableView.tag = [self.userControlArray indexOfObject:userResizableView];
}

// Called when the resizable view receives touchesEnded: or touchesCancelled:
- (void)userResizableViewDidEndEditing:(SPUserResizableView *)userResizableView{
//    NSLog(@"userResizableViewDidEndEditing");
    
}
//长按收拾触发事件
- (void)userresizableViewLongPress:(SPUserResizableView *)userResizableView{
    //必须设置为第一响应者
    [self.view becomeFirstResponder];
    
    UIMenuController *menuController = [UIMenuController sharedMenuController];

    UIMenuItem *menuItem_edit = [[UIMenuItem alloc] initWithTitle:@"编辑" action:@selector(editControl:)];
//    NSLog(@"长按选中的index ＝ %@",[NSString stringWithFormat:@"%lul",userResizableView.tag]);
    
    
    //@selector()括号中为该按钮触发的方法，该方法必须在UIVIewContrller中进行声明，就是投向的view所绑定的viewController类中必须实现这个方法
    UIMenuItem *menuItem_delete = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(deleteControl:)];

    menuController.menuItems = [NSArray arrayWithObjects: menuItem_edit, menuItem_delete,nil];
    if (isEdit) {
        [menuController setTargetRect:CGRectMake(userResizableView.frame.origin.x, userResizableView.frame.origin.y+10, userResizableView.frame.size.width, userResizableView.frame.size.height) inView:_placeholderView];//touchpos_x, touchpos_y分别为长按那点的x和y坐标   self.view为将要展示弹出框的视图

    }else{
        [menuController setTargetRect:CGRectMake(userResizableView.frame.origin.x, userResizableView.frame.origin.y+10, userResizableView.frame.size.width, userResizableView.frame.size.height) inView:self.view];//touchpos_x, touchpos_y分别为长按那点的x和y坐标   self.view为将要展示弹出框的视图

    }
    //    [menuController setTargetRect:userResizableView.frame inView:self.view];
    [menuController setMenuVisible:YES animated:YES];
    [menuController setNametag:[NSString stringWithFormat:@"%d",userResizableView.tag]];
}
#pragma mark - UIResponder
//能否更改FirstResponder,一般视图默认为NO,必须重写为YES
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

//哪些菜单能够显示
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(editControl:) || action == @selector(deleteControl:))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
#pragma mark 编辑
-(void)editControl:(id)sender{
    UIMenuController * menuController = (UIMenuController *)sender;
    NSLog(@"editControl-%@",menuController.nametag);
}
#pragma mark 删除
-(void)deleteControl:(id)sender{
    UIMenuController * menuController = (UIMenuController *)sender;
    NSLog(@"deleteControl-%@",menuController.nametag);
//    删除所有UIView
    for (UIView * view in self.view.subviews) {
        if ([view isKindOfClass:[SPUserResizableView class]]) {
            [view removeFromSuperview];
        }
        
    }
    
    [self.userControlArray removeObjectAtIndex:[menuController.nametag integerValue]];
//    添加所有用户拖出的控件
    for (SPUserResizableView *userResizableView in self.userControlArray) {
        [self.view addSubview:userResizableView];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
